
<template>

    <div>
        <el-breadcrumb separator="/" style="color: black;font-weight: 700">
            <el-breadcrumb-item >首页</el-breadcrumb-item>
            <el-breadcrumb-item>行李转盘</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>行李转盘管理</h1>
        <!--      搜索表单-->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-button type="primary" @click="openAddDialog">添加</el-button>
            </el-col>
            <el-col :span="6">
                <el-form-item label="航班号" >
                    <el-input placeholder="输入航班号" v-model="searchCriteria.META_ID" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-button type="primary" @click="searchOnSubmit">查询</el-button>
                    <el-button @click="searchOnReset">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    v-for="(item, index) in tableHeader"
                    :key="item.prop"
            >
                <template #default="scope">
                    <div
                            v-show="item.editable || scope.row.editable"
                            class="editable-row"
                    >
                        <template v-if="item.type === 'input'">
                            <el-input
                                    v-bind="{ readonly: ['ID','META_ID'].includes(item.prop) && scope.row.editable }"
                                    size="small"
                                    v-model="scope.row[item.prop]"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                      <template v-if="item.type === 'date'">
                        <el-date-picker
                            v-model="scope.row[item.prop]"
                            type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="`请输入${item.label}`"
                        @change="handleEdit(scope.$index, scope.row)"
                        />
                      </template>
                        <template v-else-if="item.type === 'select'">
                            <!-- 新增：对于类型为'select'的列 -->
                            <el-select
                                    v-model="scope.row[item.prop]"
                                    :value="scope.row[item.prop]"
                                    size="small"
                                    @change="handleEdit(scope.$index, scope.row)"
                            >
                                <el-option
                                        v-for="option in item.options"
                                        :key="option.value"
                                        :label="option.label"
                                        :value="option.value"
                                />
                            </el-select>
                        </template>
                    </div>
                    <div
                            v-show="!item.editable && !scope.row.editable"
                            class="editable-row"
                    >
                        <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button
                            v-show="!scope.row.editable"
                            size="small"
                            @click="scope.row.editable = true"
                    >编辑信息</el-button
                    >
                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="success"
                            @click="saveEditedRow(scope.row)"
                    >确定</el-button
                    >

                    <el-button
                            v-show="scope.row.editable"
                            size="small"
                            type="warning"
                            @click="cancelEdit(scope.row)"
                    >取消</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件示例 -->
      <el-pagination
          v-model="currentPage"
          :small="small"
          :disabled="disabled"
          :background="background"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total=totalElements
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-if="showPagination"
      />

        <!-- 添加飞机信息模态框 -->
        <el-dialog v-model="dialogVisible" title="添加登机口信息" width="50%" @close="resetAddForm">
            <el-form ref="addFormRef" :model="newFlight" label-width="80px">
                <el-form-item label="航班号">
                    <el-input v-model="newFlight.META_ID" placeholder="请输入航班号[只能是6位数字]"/>
                </el-form-item>
                <el-form-item label="转盘序号" >
                    <el-input v-model="newFlight.btno" placeholder="请输入转盘序号[只能是数字]"/>
                </el-form-item>
                <el-form-item label="转盘编号">
                    <el-input v-model="newFlight.code" placeholder="请输入转盘编号[只能是数字]"/>
                </el-form-item>
                <el-form-item label="预计开始">
                    <el-date-picker
                            v-model="newFlight.estr"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
                <el-form-item label="预计结束">
                    <el-date-picker
                            v-model="newFlight.eend"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="选择日期"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddHandler">确定</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
    import {onMounted, onUpdated, reactive, ref} from "vue";
    import axios from "axios";
    import {ElMessage,ElMessageBox} from "element-plus";


    const small = ref(false)
    const background = ref(true)
    const disabled = ref(false)

    const handleSizeChange = (val) => {
      console.log(`${val} items per page`)
    }
    const item = reactive({
        ID: '',
        META_ID: '',
        BTNO: '',
        CODE: '',
        ESTR: '',
        EEND: '',
        VALID: "",
        displayStatus:"",
    });
    const header = {
        prop: "key",
        label: "自定义",
        editable: false,
        type: "input",
    };
    //表头
    const tableHeader = ref([
        // {
        //     prop: "ID",
        //     label: "ID",
        //     editable: false,
        //     type: "input"
        // },
        {
            prop: "META_ID",
            label: "航班号",
            editable: false,
            type: "input",
        },
        {
            prop: "BTNO",
            label: "行李转盘序号",
            editable: false,
            type: "input"
        },
        {
            prop: "CODE",
            label: "行李转盘编号",
            editable: false,
            type: "input"
        },
        {
            prop: "ESTR",
            label: "预计开始时间",
            editable: false,
            type: "date"
        },
        {
            prop: "EEND",
            label: "预计结束时间",
            editable: false,
            type: "date"
        },
        {
            prop: "displayStatus",
            label: "状态",
            editable: false,
            type: "select", // 将类型更改为'select'
            options: [
                { label: "启用", value: 1 },
                { label: "禁用", value: 0 },
            ],
        },
    ]);
    const tableData = ref([]);

    const showPagination = ref(true);
    //分页查询
    // 分页相关状态
    const currentPage = ref(1); // 当前页码，默认为第一页
    const pageSize = ref(5); // 每页显示数量，默认为5条
    const totalElements = ref(0);
    //分页查询
    async function fetchGateData(current = currentPage.value, size = pageSize.value) {
        try {
            const response = await axios.get('/blls/page', {
                params: {
                    currentPage: current,
                    pageSize: size
                }
            });

            if (!response.data.errorCode || response.data.errorCode === "200") {
                // 更新tableData时，考虑分页数据结构
                tableData.value = response.data.data.map(blls => ({
                    ID: blls.id,
                    META_ID: blls.META_ID,
                    BTNO: blls.btno,
                    CODE: blls.code,
                    ESTR: blls.estr,
                    EEND: blls.eend,
                    VALID: blls.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: blls.valid === 1 ? '启用' : '禁用',
                }));
                totalElements.value = response.data.total;
            } else {
                ElMessage.error(response.data.msg || '获取数据失败');
                console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
            }
        } catch (error) {
            ElMessage.error('获取数据过程中发生错误');
            console.error('Error fetching data:', error);
        }
    }

    // 初始化时加载第一页数据
    onMounted(() => {
        fetchGateData();
        showPagination.value=true;
    });
    onUpdated(() => {
    });

    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handleCurrentChange(page) {
        currentPage.value = page;
        fetchGateData(page);
    }

    //添加
    const openAddDialog = () => {
        dialogVisible.value = true;
    };

    //删除
    async function deleteBllsData(ID) {
        // 使用ElMessageBox显示确认对话框
        const confirmResult = await ElMessageBox.confirm(
            '确定要删除这条飞机信息吗？',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        // 如果用户点击了确认按钮（confirm）
        if (confirmResult === 'confirm') {
            try {
                const response = await axios.delete(`/blls/${ID}`);

                if (!response.data.errorCode || response.data.errorCode === "200") {
                    await fetchGateData();
                    ElMessage.success('删除成功');
                } else {ElMessage.error('删除失败，请重试');}
            } catch (error) {
                console.error('Error deleting data:', error);
                ElMessage.error('删除失败');
            }
        }
        // 如果用户点击取消，则什么都不做，对话框自动关闭
    }


    function handleEdit(row) {
        row.editable = true;
    }
    //修改
    async function saveEditedRow(row) {
        if (row.displayStatus === '启用'  || row.displayStatus ==='禁用') {
            ElMessage.warning('请再次确认选择一次您的状态');
            return; // 停止执行保存逻辑
        }
        try {
            const updatedBlls = {
                id: row.ID,
                meta_id: row.META_ID,
                btno: row.BTNO,
                code: row.CODE,
                estr: row.ESTR,
                eend: row.EEND,
                valid: row.displayStatus,

            };
            const response = await axios.put(`/blls/update`, updatedBlls);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('更新成功');
                row.editable = false;
                await fetchGateData();
            } else {
                ElMessage.error(response.data.msg || '更新失败，请重试');
            }
        } catch (error) {
            console.error('Error updating data:', error);
            ElMessage.error('更新过程中发生错误');
        }
    }
    //取消修改按钮
    const cancelEdit = (row) => {
        row.editable = false;
    //    恢复原来数据
        Object.assign(row, {
            ID: row.ID,
            META_ID: row.META_ID,
            BTNO: row.BTNO,
            CODE: row.CODE,
            ESTR: row.ESTR,
            EEND: row.EEND,
        });
        ElMessage.warning('已取消修改');
        fetchGateData();
    };
    //查询表单
    const searchCriteria = reactive({
        META_ID: "",
    });
    async function searchOnSubmit() {
        try {
            // 确保META_ID非空
            if (!searchCriteria.META_ID ) {
                ElMessage.warning("航班号不能为空");
                return;
            }
            //输入的不是数字
            if (isNaN(searchCriteria.META_ID)) {
                ElMessage.warning("航班号必须为数字");
                return;
            }
            const response = await axios.get(`/blls/findBy/${searchCriteria.META_ID}`);
            // 根据后端实际返回结构处理数据
            if (response.data.errorCode === "400") {
                ElMessage.error(response.data.msg);
            } else {
                tableData.value = response.data.data.map(blls => ({
                    ID: blls.id,
                    META_ID: blls.META_ID,
                    BTNO: blls.btno,
                    CODE: blls.code,
                    ESTR: blls.estr,
                    EEND: blls.eend,
                    valid: blls.valid,
                    // 添加新属性用于展示，根据VALID值决定
                    displayStatus: blls.valid === 1 ? '启用' : '禁用',
                }));
                showPagination.value =false;
            }
        } catch (error) {
            ElMessage.error('查询失败，请检查网络或输入内容');
            console.error('查询错误:', error);
        }
    }
    //查询取消
    const searchOnReset =async () => {
        searchCriteria.META_ID = "";
        tableData.value = []; // 查询重置时清空表格数据
        showPagination.value = true;
        await fetchGateData();
    };


    // 添加飞机信息的对话框状态
    const dialogVisible = ref(false);
    // 重置添加表单
    const newFlight = reactive({
        META_ID: "",
        btno: "",
        code: "",
        estr: "",
        eend: "",
    });
    // 重置添加表单
    const resetAddForm = () => {
        newFlight.META_ID = "";
        newFlight.btno = "";
        newFlight.code = "";
        newFlight.estr = "";
        newFlight.eend = "";
    };

    // 确定添加飞机信息
    const onAddHandler = async () => {
        if (!newFlight.META_ID || !newFlight.btno|| !newFlight.code ||  !newFlight.estr || !newFlight.eend) {
            ElMessage.warning('请填写完整的信息');
            return;
        }
        //如果META_ID、BTNO、CODE输入的不是数字，就在对应的输入框提示
        if (isNaN(newFlight.META_ID) || isNaN(newFlight.btno) || isNaN(newFlight.code)) {
            ElMessage.error('航班号、机位号、机位号必须为数字');
            return;
        }
        //航班号必须是6位
        if (newFlight.META_ID.length !== 6) {
            ElMessage.warning('航班号格式不正确，请输入正确的格式[六位数字]');
            return;
        }

        try {
            // 发送POST请求到后端
            const response = await axios.post('/blls/insert', newFlight);
            if (response.data.errorCode === "200") {
                ElMessage.success('添加成功');
                // 成功后关闭对话框并刷新数据
                dialogVisible.value = false;
                resetAddForm();
                await fetchGateData(); // 刷新表格数据
            } else {
                ElMessage.error(response.data.msg || '添加失败');
            }
        } catch (error) {
            ElMessage.error('添加过程中发生错误');
            console.error('Addition error:', error);
        }
    };

</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 20px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>